/***
 * @param {Number} min
 * @param {Number} max
 * @return {Number} 
 */
const random=(min,max)=>{
    return parseInt(Math.random()*(max-min))
}
/***
 * @param {Number} len
 * @return {Number} 
 */

 const randomCode=len=>{
     let num='';
     while (num.length <len){
         num +=random(0,10)
     }
     return num
 }
 const arrayToTree = arr => {
    const tree = [];
    const arrJSON = {};
  
    arr.forEach(item => {
      arrJSON[item.id] = item;
    });
  
    arr.forEach(item => {
      const parent = arrJSON[item.parent_id];
      if (parent) {
        if (parent.children) {
          parent.children.push(item);
        } else {
          parent.children = [ item ];
        }
      } else {
        tree.push(item);
      }
    });
  
    return tree;
  };
  
  const getChildrenIds = (arr, id, flg = false) => {
    let ids = [];
    arr.forEach(item => {
      if (flg) {
        if (item.children) {
          ids = ids.concat(getChildrenIds(item.children, item.id, true));
        } else {
          ids.push(item.id);
        }
      } else {
        if (item.children) {
          if (item.id === id * 1) {
            ids = ids.concat(getChildrenIds(item.children, item.id, true));
          } else {
            ids = ids.concat(getChildrenIds(item.children, id));
          }
        }
      }
    });
    return ids;
  };
 module.exports={
     random,
     randomCode, 
     arrayToTree,
     getChildrenIds,
 }
